package Controleur;

import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Locale;

import javax.servlet.ServletContext;
import javax.servlet.http.*;

import Helpers.Configuration;
import JavaBean.BeanRepresentation;
import Modele.ListeRepresentations;
import Modele.ListeSpectacles;
import Modele.Representation;
import Modele.Spectacle;

public class RepresentationsServlet extends CustomServlet
{
	private static final long serialVersionUID = 1L;

	@Override
	public void executeGet(HttpServletRequest request, HttpServletResponse response)
	{
		ArrayList<BeanRepresentation> beanEnvoi = new  ArrayList<BeanRepresentation>();
		ArrayList<Representation> representations;
		DateFormat df = DateFormat.getDateInstance(DateFormat.LONG, Locale.CANADA_FRENCH);
		
		if (request.getParameter("IdSpectacle") == null)
			representations =  ((ListeRepresentations)getServletContext().getAttribute("listeRepresentations")).getRepresentations();
		else
		{
			ListeSpectacles spectacles = (ListeSpectacles)getServletContext().getAttribute("listeSpectacles");
			int id = Integer.parseInt(request.getParameter("IdSpectacle"));
			representations = spectacles.getSpectacle(id).getRepresentations();
			request.setAttribute("idSpectacle", id);
		}		
		
		int page = 1;
		int nbPages = (int)Math.ceil(representations.size() / Configuration.MAX_REPRESENTATIONS_PAGE);
		
		try
		{
			page = Integer.parseInt(request.getParameter("p"));
		}
		catch ( Exception e )
		{}
		
		if ( page > nbPages )
			page = 1;		
		
		for ( int i = ( page - 1 ) * Configuration.MAX_REPRESENTATIONS_PAGE; i < page * Configuration.MAX_REPRESENTATIONS_PAGE && i < representations.size ( ) ; i ++)
		{
			Representation r = representations.get(i);
			BeanRepresentation br = new BeanRepresentation();
			br.setArtiste(r.getSpectacle().getArtiste().getNom());
			br.setTitre(r.getTitre());
			br.setEmplacement(r.getEmplacement().getNom());
			br.setDate(df.format(r.getDate().getTime()));
			br.setIdRepresentation(r.getIdRepresentation());
			beanEnvoi.add(br);
		}
		
		request.setAttribute("representations", beanEnvoi);
		request.setAttribute("numPage", page);
		request.setAttribute("nbPages", nbPages );
	}
	
	@Override
	public void executePost(HttpServletRequest request,
			HttpServletResponse response) {
		// TODO Auto-generated method stub
		
	}
}
